package _18_剑指OfferII;

public class _112_剑指OfferII最长递增路径 {

    private int[][] matrix;

    private int[][] m = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    private int rows;

    private int cols;

    // 直接使用深度优先搜索，获取最大值
    // 并且采用记忆化搜索，获取以前遍历到的值
    public int longestIncreasingPath(int[][] matrix) {
        this.rows = matrix.length;
        this.cols = matrix[0].length;
        this.matrix = matrix;
        int res = 1;
        int[][] memo = new int[rows][cols];
        for (int i = 0; i < rows; ++i) {
            for (int j = 0; j < cols; ++j) {
                res = Math.max(res, dfs(i, j, memo));
            }
        }
        return res;
    }

    private int dfs(int row, int col, int[][] memo) {
        // 记忆化搜索，获取上次的值
        if (memo[row][col] != 0) {
            return memo[row][col];
        }
        ++memo[row][col];

        for (int[] ints : m) {
            int newRow = row + ints[0];
            int newCol = col + ints[1];
            if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && matrix[newRow][newCol] > matrix[row][col]) {
                memo[row][col] = Math.max(memo[row][col], dfs(newRow, newCol, memo) + 1);
            }
        }
        return memo[row][col];
    }

}
